<?php
namespace Rcard\Model;

use Think\Model;
use Think\Hook;


class RcardModel extends Model
{
    public function getList($map = array(), $page = 1, $r = 20, $order = 'id desc')
    {

        $totalCount = D('RcardType')->where($map)->count();
        if ($totalCount) {
            $dataList = D('RcardType')->where($map)->page($page, $r)->order($order)->select();
            return array($this->_initSelectData($dataList), $totalCount);
        }
        return array(null, 0);
    }

    public function getRcardList($map = array(), $page = 1, $r = 20, $order = 'id desc')
    {

        $totalCount = D('Rcard')->where($map)->count();
        if ($totalCount) {
            $dataList = D('Rcard')->where($map)->page($page, $r)->order($order)->select();
            foreach ($dataList as &$v) {
                $v['action'] = D('RcardType')->where(array('id' => $v['rcard_type']))->find();
                $v['action'] = $v['action']['action'];
            }
            return array($this->_initSelectData($dataList), $totalCount);
        }
        return array(null, 0);
    }


    private function _initSelectData($dataList = array())
    {
        //dump($dataList);exit;
        //$rcard_type_id = array_column($dataList, 'invite_type');
        // $map['id'] = array('in', $rcard_type_id);

        foreach ($dataList as &$val) {
            $val['action'] = json_decode($val['action'], true);
            foreach ($val['action'] as &$v) {
                $v['FIELD'] = D('UcenterScoreType')->where(array('id' => $v['FIELD']))->field('title,unit')->find();
                if ($v['UNIT'] >= 0) {
                    $v = $v['FIELD']['title'] . '+' . $v['UNIT'] . $v['FIELD']['unit'];
                } else {
                    $v = $v['FIELD']['title'] . $v['UNIT'] . $v['FIELD']['unit'];
                }

            };
            $val['action'] = implode(' ', $val['action']);
            if ($val['uid'] > 0) {
                $val['buyer'] = get_nickname($val['uid']);
            } else {
                $val['buyer'] = get_nickname( -$val['uid']) . '后台生成';
            }
        }
        unset($val);
        return $dataList;
    }


    public function createCodeAdmin($data = array(), $num = 1)
    {
        $map['status'] = 1;
        $map['id'] = $data['rcard_type'];
        $rcard_type = D('Rcard/RcardType')->getSimpleList($map, 'rcardlen,title');


        $data['uid'] = -is_login(); //管理员后台生成，以负数uid标记
        $data['title']=$rcard_type[0]['title'];
        $dataList = array();
        for ($i = 0; $i < $data['num']; $i++) {
            do {
                $dataList[] = $this->createOneCode($data, $rcard_type[0]['rcardlen']);
            } while (count($dataList) < $num);
        }
        $res = $this->addAll($dataList);
        if ($res) {
            $result['status'] = 1;
            $result['url'] = U('Admin/Rcard/creatercard', array('status' => 1, 'buyer' => -1));
        } else {
            $result['status'] = 0;
            $result['info'] = "生成邀请码时失败！" . $this->getError();
        }
        return $result;
    }


    private function createOneCode($data = array(), $length)
    {


        $length = $length ? $length : 11;
        do {
            //生成随机数
            $map['code'] = create_rand($length);
        } while ($this->where($map)->count());
        $data['code'] = $map['code'];
        $data['status'] = 1;
        $data['create_time'] = time();
        $data = $this->create($data);
        return $data;
    }

    public function exchargeRcard($cdk)
    {
        $Rcard = D('Rcard')->where(array('code' => $cdk, 'status' => 1))->find();
        if (empty($Rcard)) {
            $Rcard = D('Rcard')->where(array('code' => $cdk))->find();
            if ($Rcard) {
                switch ($Rcard['status']) {
                    case -1:
                        $result['status'] = 0;
                        $result['info'] = '该KDKEY已被删除！';
                        break;
                    case 0:
                        $result['status'] = 0;
                        $result['info'] = '您的CDKEY已被禁用！';
                        break;
                    case 2:
                        $result['status'] = 0;
                        $result['info'] = '您的CDKEY已被占用！';
                        break;
                }
            } else {
                $result['status'] = 0;
                $result['info'] = '您的CDK有误！';
            }
        } else {
            $RcardType = D('RcardType')->where(array('id' => $Rcard['rcard_type'], 'status' => 1))->find();
            if (empty($RcardType)) {
                $result['status'] = 0;
                $result['info'] = '该类型卡密已被禁用或删除！';
            } else {
                $rs = $this->do_rcard($Rcard['id'], $RcardType['action']);
                if ($rs) {
                    $RcardType['action'] = json_decode($RcardType['action'], true);
                    foreach ($RcardType['action'] as &$v) {
                        $v['FIELD'] = D('UcenterScoreType')->where(array('id' => $v['FIELD']))->field('title,unit')->find();
                        if ($v['UNIT'] > 0) {
                            $v = $v['FIELD']['title'] . '+' . $v['UNIT'] . $v['FIELD']['unit'];
                        } else {
                            $v = $v['FIELD']['title'] . $v['UNIT'] . $v['FIELD']['unit'];
                        }

                    };
                    $RcardType['action'] = implode(' ', $RcardType['action']);

                    $data['uid'] = is_login();
                    $data['rcard_type'] = $RcardType['title'];
                    $data['rcard_title'] = $Rcard['title'];
                    $data['code'] = $cdk;
                    $data['action'] = $RcardType['action'];
                    $data['create_time'] = time();
                    D('RcardRecord')->add($data);
                    $result['status'] = 1;
                    $result['info'] = '兑换成功！';
                    D('Common/Message')->sendMessageWithoutCheckSelf(is_login(), '成功兑换卡密！', $title = '您兑换了卡密获得：' . $RcardType['action'], 'rcard/index/record', $url_args = array(), is_login(), 2);
                } else {
                    $result['status'] = 0;
                    $result['info'] = '兑换失败！';
                }
            }
        }
        return $result;
    }

    private function do_rcard($rcardId = "", $action = "")
    {
        $action = json_decode($action, true);
        foreach ($action as &$v) {

            if ($v['UNIT'] >= 0) {
                $res = D('Member')->where(array('uid' => is_login()))->setInc('score' . $v['FIELD'], $v['UNIT']);
            } else {
                $v['UNIT'] = abs($v['UNIT']);
                $res = D('Member')->where(array('uid' => is_login()))->setDec('score' . $v['FIELD'], $v['UNIT']);
            }
        }
        D('Rcard')->where(array('id' => $rcardId))->setField('status', 2);
        return $res;
    }

}